<template>
  <div class="notifications-page">
    <div class="page-header">
      <h1>通知中心</h1>
      <div class="header-actions">
        <button @click="refreshNotifications" class="btn-refresh">
          <span class="refresh-icon">🔄</span>
          刷新
        </button>
        <button @click="markAllAsRead" class="btn-mark-all">
          <span class="mark-icon">✓</span>
          全部已读
        </button>
        <button @click="clearAllNotifications" class="btn-clear-all">
          <span class="clear-icon">🗑️</span>
          清空
        </button>
      </div>
    </div>

    <!-- 通知统计 -->
    <div class="notification-stats">
      <div class="stat-card">
        <div class="stat-icon">📊</div>
        <div class="stat-content">
          <div class="stat-number">{{ totalNotifications }}</div>
          <div class="stat-label">总通知</div>
          </div>
          </div>
      <div class="stat-card">
        <div class="stat-icon">🔔</div>
        <div class="stat-content">
          <div class="stat-number">{{ unreadCount }}</div>
          <div class="stat-label">未读</div>
          </div>
          </div>
      <div class="stat-card">
        <div class="stat-icon">🎫</div>
        <div class="stat-content">
          <div class="stat-number">{{ ticketNotifications }}</div>
          <div class="stat-label">工单通知</div>
          </div>
          </div>
      <div class="stat-card">
        <div class="stat-icon">⚙️</div>
        <div class="stat-content">
          <div class="stat-number">{{ systemNotifications }}</div>
          <div class="stat-label">系统通知</div>
          </div>
          </div>
        </div>

    <!-- 筛选和搜索 -->
    <div class="notification-filters">
      <div class="filter-group">
        <label>类型筛选:</label>
        <select v-model="selectedType" @change="filterNotifications">
          <option value="">全部</option>
          <option value="ticket">工单</option>
          <option value="system">系统</option>
          <option value="user">用户</option>
          <option value="general">一般</option>
        </select>
    </div>

      <div class="filter-group">
        <label>优先级筛选:</label>
        <select v-model="selectedPriority" @change="filterNotifications">
          <option value="">全部</option>
          <option value="urgent">紧急</option>
          <option value="high">高</option>
          <option value="normal">普通</option>
          <option value="low">低</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label>状态筛选:</label>
        <select v-model="selectedStatus" @change="filterNotifications">
          <option value="">全部</option>
          <option value="unread">未读</option>
          <option value="read">已读</option>
        </select>
      </div>
      
      <div class="search-group">
        <input 
          type="text" 
          v-model="searchQuery" 
          @input="filterNotifications"
          placeholder="搜索通知..."
          class="search-input"
        >
        <button @click="clearFilters" class="btn-clear-filters">
          清除筛选
        </button>
        </div>
        </div>

    <!-- 通知列表 -->
    <div class="notifications-container">
      <div v-if="filteredNotifications.length === 0" class="empty-state">
        <div class="empty-icon">📭</div>
        <h3>暂无通知</h3>
        <p v-if="hasActiveFilters">尝试调整筛选条件</p>
        <p v-else>您还没有收到任何通知</p>
          </div>
      
      <div v-else class="notifications-list">
        <div 
          v-for="notification in paginatedNotifications" 
          :key="notification.id"
          :class="['notification-card', {
            'unread': !notification.isRead,
            'high-priority': notification.priority === 'high' || notification.priority === 'urgent',
            'urgent': notification.priority === 'urgent'
          }]"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-header">
            <div class="notification-icon">
              <span :class="getNotificationIconClass(notification.type)">
                {{ getNotificationEmoji(notification.type) }}
              </span>
            </div>
            <div class="notification-title">
              {{ notification.title }}
              <span v-if="!notification.isRead" class="unread-badge">未读</span>
              <span v-if="notification.priority === 'urgent'" class="urgent-badge">紧急</span>
              <span v-else-if="notification.priority === 'high'" class="priority-badge">高优先级</span>
            </div>
            <div class="notification-time">
              {{ formatTime(notification.timestamp) }}
            </div>
          </div>
          
          <div class="notification-content">
            <p>{{ notification.content }}</p>
            <div v-if="notification.sender" class="notification-sender">
              来自: {{ notification.sender.username || notification.sender.name || '系统' }}
            </div>
          </div>
          
          <div class="notification-footer">
            <div class="notification-meta">
              <span class="notification-category">
                {{ getCategoryName(notification.category) }}
              </span>
              <span class="notification-type">
                {{ getTypeName(notification.type) }}
              </span>
            </div>
            <div class="notification-actions">
              <button 
                v-if="!notification.isRead"
                @click.stop="markAsRead(notification.id)"
                class="btn-mark-read"
                title="标记为已读"
              >
                ✓ 已读
              </button>
              <button 
                @click.stop="removeNotification(notification.id)"
                class="btn-remove"
                title="删除通知"
              >
                🗑️ 删除
              </button>
          </div>
        </div>
      </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination">
        <button 
          @click="currentPage--" 
          :disabled="currentPage === 1"
          class="btn-prev"
        >
          上一页
        </button>
        
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        
        <button 
          @click="currentPage++" 
          :disabled="currentPage === totalPages"
          class="btn-next"
        >
          下一页
        </button>
          </div>
        </div>
        
    <!-- 通知设置 -->
    <div class="notification-settings-section">
      <h2>通知设置</h2>
      <div class="settings-grid">
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.desktopNotifications"
              @change="updateSettings"
            >
            桌面通知
          </label>
        </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.soundNotifications"
              @change="updateSettings"
            >
            声音提示
          </label>
          </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.ticketNotifications"
              @change="updateSettings"
            >
            工单通知
          </label>
          </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.systemNotifications"
              @change="updateSettings"
            >
            系统通知
          </label>
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useNotificationsStore } from '../store/notifications.js'
import messageHandler from '../services/notificationHandler.js'

export default {
  name: 'NotificationsPage',
  setup() {
    const notificationsStore = useNotificationsStore()

    // 响应式数据
    const selectedType = ref('')
    const selectedPriority = ref('')
    const selectedStatus = ref('')
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const settings = ref({
      desktopNotifications: true,
      soundNotifications: true,
      ticketNotifications: true,
      systemNotifications: true
    })

    // 计算属性
    const totalNotifications = computed(() => notificationsStore.notifications.length)
    const unreadCount = computed(() => notificationsStore.unreadCount)
    
    const ticketNotifications = computed(() => 
      notificationsStore.getNotificationsByCategory('ticket').length
    )
    
    const systemNotifications = computed(() => 
      notificationsStore.getNotificationsByCategory('system').length
    )
    
    const filteredNotifications = computed(() => {
      let filtered = [...notificationsStore.notifications]

      // 类型筛选
      if (selectedType.value) {
        filtered = filtered.filter(n => n.category === selectedType.value)
      }

      // 优先级筛选
      if (selectedPriority.value) {
        filtered = filtered.filter(n => n.priority === selectedPriority.value)
      }

      // 状态筛选
      if (selectedStatus.value === 'unread') {
        filtered = filtered.filter(n => !n.isRead)
      } else if (selectedStatus.value === 'read') {
        filtered = filtered.filter(n => n.isRead)
      }
      
      // 搜索筛选
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(n => 
          n.title.toLowerCase().includes(query) ||
          n.content.toLowerCase().includes(query) ||
          (n.sender && n.sender.username && n.sender.username.toLowerCase().includes(query))
        )
      }
      
      // 按时间排序
      return filtered.sort((a, b) => b.timestamp - a.timestamp)
    })
    
    const totalPages = computed(() => 
      Math.ceil(filteredNotifications.value.length / pageSize.value)
    )

    const paginatedNotifications = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredNotifications.value.slice(start, end)
    })
    
    const hasActiveFilters = computed(() => 
      selectedType.value || selectedPriority.value || selectedStatus.value || searchQuery.value
    )
    
    // 方法
    const filterNotifications = () => {
      currentPage.value = 1 // 重置到第一页
    }
    
    const clearFilters = () => {
      selectedType.value = ''
      selectedPriority.value = ''
      selectedStatus.value = ''
      searchQuery.value = ''
      currentPage.value = 1
    }

    const getNotificationIconClass = (type) => {
      const iconMap = {
        'success': 'icon-success',
        'error': 'icon-error',
        'warning': 'icon-warning',
        'info': 'icon-info',
        'ticket': 'icon-ticket',
        'system': 'icon-system',
        'user': 'icon-user'
      }
      return iconMap[type] || 'icon-info'
    }
    
    const getNotificationEmoji = (type) => {
      const emojiMap = {
        'success': '✅',
        'error': '❌',
        'warning': '⚠️',
        'info': 'ℹ️',
        'ticket': '🎫',
        'system': '⚙️',
        'user': '👤'
      }
      return emojiMap[type] || '📢'
    }
    
    const getCategoryName = (category) => {
      const categoryMap = {
        'general': '一般',
        'ticket': '工单',
        'system': '系统',
        'user': '用户',
        'security': '安全'
      }
      return categoryMap[category] || category
    }
    
    const getTypeName = (type) => {
      const typeMap = {
        'success': '成功',
        'error': '错误',
        'warning': '警告',
        'info': '信息',
        'ticket': '工单',
        'system': '系统',
        'user': '用户'
      }
      return typeMap[type] || type
    }
    
    const formatTime = (timestamp) => {
      const now = Date.now()
      const diff = now - timestamp
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return new Date(timestamp).toLocaleDateString()
      }
    }
    
    const handleNotificationClick = (notification) => {
      // 标记为已读
      if (!notification.isRead) {
        markAsRead(notification.id)
      }
      
      // 根据通知类型进行不同的处理
      const { category, data } = notification
      
      switch (category) {
        case 'ticket':
          if (data.ticketId) {
            window.location.href = `/ticket/${data.ticketId}`
          }
          break
        case 'user':
          window.location.href = '/users'
          break
        case 'system':
          window.location.href = '/settings'
          break
        default:
          // 保持在当前页面
          break
      }
    }
    
    const markAsRead = (notificationId) => {
      notificationsStore.markAsRead(notificationId)
      messageHandler.markAsRead(notificationId)
    }
    
    const markAllAsRead = () => {
      notificationsStore.markAllAsRead()
    }
    
    const removeNotification = (notificationId) => {
      notificationsStore.removeNotification(notificationId)
    }
    
    const clearAllNotifications = () => {
      if (confirm('确定要清空所有通知吗？')) {
        notificationsStore.clearAllNotifications()
      }
    }
    
    const refreshNotifications = () => {
      // 重新加载通知
      notificationsStore.initialize()
    }
    
    const loadSettings = () => {
      const savedSettings = localStorage.getItem('notification-settings')
      if (savedSettings) {
        try {
          settings.value = { ...settings.value, ...JSON.parse(savedSettings) }
      } catch (error) {
          console.error('❌ 加载通知设置失败:', error)
        }
      }
    }
    
    const saveSettings = () => {
      try {
        localStorage.setItem('notification-settings', JSON.stringify(settings.value))
      } catch (error) {
        console.error('❌ 保存通知设置失败:', error)
      }
    }
    
    const updateSettings = () => {
      saveSettings()
    }
    
    // 生命周期
    onMounted(() => {
      notificationsStore.initialize()
      loadSettings()
      
      // 启动消息处理器
      messageHandler.start()
    })
    
    onUnmounted(() => {
      // 停止消息处理器
      messageHandler.stop()
    })

    return {
      selectedType,
      selectedPriority,
      selectedStatus,
      searchQuery,
      currentPage,
      settings,
      totalNotifications,
      unreadCount,
      ticketNotifications,
      systemNotifications,
      filteredNotifications,
      totalPages,
      paginatedNotifications,
      hasActiveFilters,
      filterNotifications,
      clearFilters,
      getNotificationIconClass,
      getNotificationEmoji,
      getCategoryName,
      getTypeName,
      formatTime,
      handleNotificationClick,
      markAsRead,
      markAllAsRead,
      removeNotification,
      clearAllNotifications,
      refreshNotifications,
      updateSettings
    }
  }
}
</script>

<style scoped>
.notifications-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #eee;
}

.page-header h1 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn-refresh, .btn-mark-all, .btn-clear-all {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-refresh {
  background: #007bff;
  color: white;
}

.btn-refresh:hover {
  background: #0056b3;
}

.btn-mark-all {
  background: #28a745;
  color: white;
}

.btn-mark-all:hover {
  background: #218838;
}

.btn-clear-all {
  background: #dc3545;
  color: white;
}

.btn-clear-all:hover {
  background: #c82333;
}

.notification-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.notification-filters {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group, .search-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.filter-group select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 200px;
}

.btn-clear-filters {
  padding: 8px 16px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-clear-filters:hover {
  background: #545b62;
}

.notifications-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin: 0 0 12px 0;
  color: #333;
}

.notifications-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.notification-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.2s;
}

.notification-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.notification-card.unread {
  border-left: 4px solid #007bff;
  background: #f8f9ff;
}

.notification-card.high-priority {
  border-left: 4px solid #ffc107;
}

.notification-card.urgent {
  border-left: 4px solid #dc3545;
  background: #fff5f5;
}

.notification-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.notification-icon {
  font-size: 20px;
}

.notification-title {
  flex: 1;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.unread-badge {
  background: #007bff;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
}

.urgent-badge {
  background: #dc3545;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
}

.priority-badge {
  background: #ffc107;
  color: #333;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.notification-content {
  margin-bottom: 16px;
}

.notification-content p {
  margin: 0 0 8px 0;
  color: #666;
  line-height: 1.5;
}

.notification-sender {
  font-size: 12px;
  color: #999;
}

.notification-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.notification-actions {
  display: flex;
  gap: 8px;
}

.btn-mark-read, .btn-remove {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.btn-mark-read {
  background: #28a745;
  color: white;
}

.btn-mark-read:hover {
  background: #218838;
}

.btn-remove {
  background: #dc3545;
  color: white;
}

.btn-remove:hover {
  background: #c82333;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.btn-prev, .btn-next {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-prev:hover, .btn-next:hover {
  background: #f8f9fa;
}

.btn-prev:disabled, .btn-next:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.notification-settings-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.notification-settings-section h2 {
  margin: 0 0 20px 0;
  color: #333;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.setting-item label {
  display: flex;
  align-items: center;
    gap: 8px;
  cursor: pointer;
  font-size: 14px;
}
</style>